﻿package net.wangit.dev.dataprivilege;

import net.wangit.MapList;
import net.wangit.Unit;
import net.wangit.context.ActionContext;
import net.wangit.context.ActionContextHelper;
import net.wangit.dev.ConsoleDomainUtil;
import net.wangit.dev.LockUtil;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.util.DBHelper;
import net.wangit.support.UnitInterceptor;
import net.wangit.util.Checker;

public class DataPrivilegeUI implements UnitInterceptor {

	public static final String KEY = "net.wangit.dev.dataprivilege.DataPrivilegeUI.dpid";
	private static final String SQL_CONFIG = "select * from DPCONFIG where dpid=?";
	private static final String SQL_ITEM = "select * from DP where dpid=?";

	public DataPrivilegeUI() {
	}

	public String intercept(ActionContext ac, Unit unit) throws Exception {
		String domain = ConsoleDomainUtil.getDomain(ac);
		String source = ac.getRequestParameter("src");
		boolean copy = !Checker.isEmpty(source);
		String id = copy ? source : ActionContextHelper.getRequest2Session(ac,
				"dpid", DataPrivilegeUI.KEY, null);
		String unitShowMode = unit.getShowMode();
		Unit dps = (Unit) unit.getElement("dps").getObject();
		if (!copy && "a".equals(unitShowMode)) {
			String groupId = ac.getRequestParameter("groupid");
			unit.getElement("gid").setDefaultValue(groupId);
		} else if (unit.getData() == null) {
			DB db = DBHelper.getDomainDB(domain);
			MapList configData = db.query(DataPrivilegeUI.SQL_CONFIG, id, 2);
			MapList enumerationData = db.query(DataPrivilegeUI.SQL_ITEM, id, 2);
			unit.setData(configData);
			dps.setData(enumerationData);
			if (copy) {
				configData.put(0, "dpid", "");
				configData.put(0, "l", "0");
			}
		}
		LockUtil.setElements(ac, unit, new Object[][] {
				new Object[] { unit, "save" },
				new Object[] { dps, "add", "remove" } });
		return unit.write(ac);
	}
}
